<template>
  <div class="home-page">
    <van-nav-bar
      title="数独游戏"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    >
      <template #right>
        <van-icon name="user-o" size="18" />
      </template>
    </van-nav-bar>
    
    <div class="page-content">
      <div class="game-logo">
        <img src="../assets/logo.png" alt="数独游戏" />
      </div>
      
      <h1 class="game-title">数独挑战</h1>
      
      <div class="difficulty-selection">
        <h3>选择难度</h3>
        <div class="difficulty-buttons">
          <van-button 
            type="primary" 
            size="small" 
            :plain="selectedLevel !== 'easy'"
            @click="selectLevel('easy')"
          >
            简单
          </van-button>
          <van-button 
            type="primary" 
            size="small" 
            :plain="selectedLevel !== 'medium'"
            @click="selectLevel('medium')"
          >
            中等
          </van-button>
          <van-button 
            type="primary" 
            size="small" 
            :plain="selectedLevel !== 'hard'"
            @click="selectLevel('hard')"
          >
            困难
          </van-button>
        </div>
      </div>
      
      <div class="action-buttons">
        <van-button 
          type="primary" 
          block 
          @click="startNewGame"
        >
          开始游戏
        </van-button>
        
        <van-button 
          type="default" 
          block 
          @click="goToLeaderboard"
          class="mt-10"
        >
          排行榜
        </van-button>
        
        <van-button 
          v-if="!isLoggedIn"
          type="default" 
          block 
          @click="goToLogin"
          class="mt-10"
        >
          登录/注册
        </van-button>
      </div>
      
      <div class="game-description mt-20">
        <h3>游戏说明</h3>
        <p>数独是一种逻辑性的数字游戏，目标是在9×9的方格中填入1到9的数字，使每行、每列和每个3×3的方格都包含1到9的数字，且每个数字只能出现一次。</p>
      </div>
    </div>
    
    <footer class="game-footer">
      <p>© 2025 数独游戏 - 微信小游戏</p>
    </footer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../store/user';
import { useGameStore } from '../store/game';
import { showToast, showFailToast, closeToast, showDialog } from 'vant';
import WechatUtil from '../utils/wechat';

const router = useRouter();
const userStore = useUserStore();
const gameStore = useGameStore();

const selectedLevel = ref('easy');
const isLoggedIn = ref(userStore.isLoggedIn);

// 选择难度
const selectLevel = (level) => {
  selectedLevel.value = level;
};

// 开始新游戏
const startNewGame = async () => {
  showToast({
    message: '正在准备游戏...',
    forbidClick: true,
    type: 'loading',
  });

  try {
    let userId;
    
    // 获取用户ID：已登录用户使用真实ID，游客使用临时ID
    if (userStore.isLoggedIn && userStore.userInfo?.id) {
      userId = userStore.userInfo.id;
    } else {
      // 为游客生成或获取临时用户ID
      userId = getGuestUserId();
    }
    
    const level = selectedLevel.value;
    
    // 使用新的游戏store方法获取下一个题目
    const success = await gameStore.newGame(level, userId);
    
    if (success) {
      router.push('/game');
    } else {
      closeToast();
      showDialog({
        title: '提示',
        message: '没有可用的新题目，请稍后再试',
        confirmButtonText: '确定'
      });
    }
  } catch (error) {
    console.error('开始游戏错误', error);
    closeToast();
    
    const errorMessage = error.message || '开始游戏失败，请重试';
    showDialog({
      title: '游戏启动失败',
      message: errorMessage,
      confirmButtonText: '确定'
    });
  }
};

// 获取游客用户ID
const getGuestUserId = () => {
  // 从localStorage获取或生成游客ID
  let guestId = localStorage.getItem('guest_user_id');
  
  if (!guestId) {
    // 生成游客ID：guest_ + 时间戳 + 随机数
    guestId = `guest_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    localStorage.setItem('guest_user_id', guestId);
  }
  
  return guestId;
};

// 前往排行榜
const goToLeaderboard = () => {
  router.push('/leaderboard');
};

// 前往登录页
const goToLogin = () => {
  router.push('/login');
};

// 点击左侧按钮
const onClickLeft = () => {
  // 首页不需要返回功能
};

// 点击右侧按钮
const onClickRight = () => {
  if (isLoggedIn.value) {
    router.push('/profile');
  } else {
    router.push('/login');
  }
};

onMounted(async () => {
  // 获取用户信息
  if (userStore.isLoggedIn && !userStore.userInfo) {
    await userStore.fetchUserInfo();
  }
  
  isLoggedIn.value = userStore.isLoggedIn;
  
  // 设置微信分享
  if (WechatUtil.isWechatBrowser()) {
    try {
      // 这里应该调用后端接口获取微信JSSDK配置
      // const res = await getWxConfig(window.location.href);
      // await WechatUtil.init(res.data);
      
      WechatUtil.setShareInfo({
        title: '数独挑战 - 锻炼你的大脑',
        desc: '来挑战数独游戏，提升你的逻辑思维能力！',
        link: window.location.href,
        imgUrl: '/logo.png'
      });
    } catch (error) {
      console.error('初始化微信JSSDK失败', error);
    }
  }
});
</script>

<style scoped>
.home-page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.game-logo {
  text-align: center;
  margin: 20px 0;
}

.game-logo img {
  width: 120px;
  height: 120px;
}

.game-title {
  text-align: center;
  margin-bottom: 30px;
  color: #1989fa;
}

.difficulty-selection {
  margin-bottom: 30px;
}

.difficulty-selection h3 {
  margin-bottom: 10px;
  text-align: center;
}

.difficulty-buttons {
  display: flex;
  justify-content: space-around;
}

.action-buttons {
  margin-bottom: 30px;
}

.game-description {
  background-color: #f2f3f5;
  padding: 15px;
  border-radius: 8px;
}

.game-description h3 {
  margin-bottom: 10px;
}

.game-footer {
  text-align: center;
  padding: 10px 0;
  color: #969799;
  font-size: 12px;
  background-color: #fff;
}
</style>
